//
//  ViewController.m
//  WorldCup
//
//  Created by Mac on 15/11/20.
//  Copyright © 2015年 riverlj. All rights reserved.
//

#import "ViewController.h"
#import "TeamCell.h"
#import <CoreData/CoreData.h>
#import "Team.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate,NSFetchedResultsControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addButton;
@property (nonatomic, strong)NSFetchedResultsController *fetchedResultsController;
@end

@implementation ViewController
- (IBAction)addTeam:(UIBarButtonItem *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Secret Team" message:@"Add a new team" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
       textField.placeholder = @"Team Name";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Qualifying Zone";
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *nameTextField = alert.textFields.firstObject;
        UITextField *zoneTextField = alert.textFields[1];
        Team *team = [[Team alloc]initWithEntity:[NSEntityDescription entityForName:@"Team" inManagedObjectContext:self.managedContext] insertIntoManagedObjectContext:self.managedContext];
        team.teamName = nameTextField.text;
        team.qualifyingZone = zoneTextField.text;
        team.imageName = @"wenderland-flag";
        [self.managedContext save:nil];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Team" inManagedObjectContext:self.managedContext];
    
     [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"teamName" ascending:YES];
    NSSortDescriptor *scoreSort = [[NSSortDescriptor alloc] initWithKey:@"wins" ascending:NO];
    NSSortDescriptor *zoneSort = [[NSSortDescriptor alloc] initWithKey:@"qualifyingZone" ascending:YES];
    NSArray *sortDescriptors = @[zoneSort, scoreSort, sortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    
    self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedContext sectionNameKeyPath:@"qualifyingZone" cacheName:@"worldCup"];
    self.fetchedResultsController.delegate =self;
    [self.fetchedResultsController performFetch:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.fetchedResultsController.sections.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return[sectionInfo numberOfObjects];
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TeamCell *cell = [tableView dequeueReusableCellWithIdentifier:@"teamCellReuseIdentifier" forIndexPath:indexPath];
    Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.teamLabel.text = team.teamName;
    cell.scoreLabel.text = [NSString stringWithFormat:@"wins:%@",team.wins];
    cell.imageView.image = [UIImage imageNamed:team.imageName];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSNumber *wins = team.wins;
    team.wins = [NSNumber numberWithInteger:[wins integerValue] + 1];
    [self.managedContext save:nil];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    id sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
    return [sectionInfo name];
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (motion == UIEventSubtypeMotionShake) {
        self.addButton.enabled = true;
    }
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView beginUpdates];
}

-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath{
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            break;
        case NSFetchedResultsChangeUpdate:{
            TeamCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            Team *team = [self.fetchedResultsController objectAtIndexPath:indexPath];
            cell.teamLabel.text = team.teamName;
            cell.scoreLabel.text = [NSString stringWithFormat:@"wins:%@",team.wins];
            cell.imageView.image = [UIImage imageNamed:team.imageName];
   
        }
            break;
        case NSFetchedResultsChangeMove:{
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
    }
}

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView endUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type{
    switch (type) {
        case 1:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case 2:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        default:
            break;
    }
}

@end
